package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.bean.Picture;
import com.demo.common.Result;
import com.demo.ex.*;
import com.demo.mapper.PictureMapper;
import com.demo.service.PictureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {
    @Autowired
    PictureMapper pictureMapper;

    /**
     * 头像文件大小的上限值(1MB)
     */
    public static final int AVATAR_MAX_SIZE = 1 * 1024 * 1024;
    /**
     * 允许上传的图片的文件类型
     */
    public static final List<String> AVATAR_TYPES = new ArrayList<String>();

    /** 初始化允许上传的头像的文件类型 */
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/jpg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
        AVATAR_TYPES.add("image/pjpeg");
        AVATAR_TYPES.add("image/x-png");
    }

    @Override
    public Picture slectPByName(String name) {
        //根据参数调用方法
        Picture picture = pictureMapper.slectPByName(name);
        if (picture == null) {
            return null;
        }
        return picture;
    }


    public Result newsImage(MultipartFile file, String name) {
        // 判断上传的文件是否为空
        if (file.isEmpty()) {
            // 是：抛出异常
            throw new FileEmptyException("上传的文件不允许为空");
        }
        // 判断上传的文件大小是否超出限制值
        if (file.getSize() > AVATAR_MAX_SIZE) { // getSize()：返回文件的大小，以字节为单位
            // 是：抛出异常
            throw new FileSizeException("不允许上传超过" + (AVATAR_MAX_SIZE / 1024) + "KB的头像文件");
        }
        // 判断上传的文件类型是否超出限制
        String contentType = file.getContentType();
        log.info("文件类型:{}", contentType);
        // boolean contains(Object o)：当前列表若包含某元素，返回结果为true；若不包含该元素，返回结果为false
        if (!AVATAR_TYPES.contains(contentType)) {
            // 是：抛出异常
            throw new FileTypeException("不支持使用该类型的文件作为头像，允许的文件类型：" + AVATAR_TYPES);
        }
        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String parent = jarF.getParentFile().toString() + "/classes/static/images/";
        //D:\java\idea\WorkSpace\springBootData\target/classes/static/images/
        System.out.println(parent);
        // 保存头像文件的文件夹
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        // 保存的头像文件的文件名
//        String suffix = "";
//        //查找.的下标
//        int beginIndex = originalFilename.lastIndexOf(".");
//        if (beginIndex > 0) {
//          // 上传的源文件名字
//            //substring(2)这个表示截掉前两个，得到后边的新字符串,得到文件名后缀
//            suffix = originalFilename.substring(beginIndex);
//            log.info("suffix的值:{}",suffix);
//        }
        //查询服务器是否有文件
        Picture picture = pictureMapper.slectPByName(name);
        String fileUrl = parent + originalFilename;
        log.info("fileUrl:{}", fileUrl);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (null == picture) {
            picture = new Picture();
            picture.setName(originalFilename);
            picture.setUrl(originalFilename);
            picture.setCreateDate(sdf.format(new Date()));
            if (pictureMapper.savePicture(picture) < 0) {
                throw new FileUploadIOException("文件保存失败");
            }
        }else {
            picture.setState(1);
            UpdateWrapper<Picture> wrapper = new UpdateWrapper();
            wrapper.eq("name",originalFilename);
            pictureMapper.update(picture,wrapper);
        }
        File dest = new File(dir, originalFilename);
        // 执行保存头像文件
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            // 抛出异常
            throw new FileStateException("文件状态异常，可能文件已被移动或删除");
        } catch (IOException e) {
            // 抛出异常
            throw new FileUploadIOException("上传文件时读写错误，请稍后重新尝试");
        }
      /*// 头像路径
        String avatar = "/images/book/" + filename;
        // 返回成功头像路径*/
        return  Result.ok(parent + file.getOriginalFilename());
    }

    @Override
    public Result delImage(String fileName) {
        Picture picture = pictureMapper.slectPByName(fileName);
        if (null == picture) {
            throw new FileStateException("此图片不存在!");
        } else {
            //获取jar包所在目录
            ApplicationHome h = new ApplicationHome(getClass());
            File jarF = h.getSource();
            //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
            String url = jarF.getParentFile().toString() + "/classes/static/images/" + picture.getUrl();
            File file = new File(url);
            if (file.exists()) {//文件是否存在
//                log.info("i={}",i);
                if ( pictureMapper.delImage(fileName)>0 && file.delete()) {
                    return  Result.ok("删除成功");
                } else {
                    return  Result.error("删除失败");
                }
            } else {
                throw new FileStateException("此图片不存在!");
            }
        }
    }
    @Override
    public Picture selectOne(String fileName){
        QueryWrapper<Picture> wrapper = new QueryWrapper();
        wrapper.eq("name",fileName).eq("state",1);
        return pictureMapper.selectOne(wrapper);
    }

}
